package com.youlai.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.system.common.result.PageResult;
import com.youlai.system.common.result.Result;
import com.youlai.system.common.util.ExcelUtils;
import com.youlai.system.model.entity.CarUser;
import com.youlai.system.model.entity.SysUser;
import com.youlai.system.model.form.CarUserForm;
import com.youlai.system.model.form.UserForm;
import com.youlai.system.model.query.CarUserPageQuery;
import com.youlai.system.model.query.UserPageQuery;
import com.youlai.system.model.vo.*;
import com.youlai.system.plugin.dupsubmit.annotation.PreventDuplicateSubmit;
import com.youlai.system.plugin.easyexcel.UserAppImportListener;
import com.youlai.system.plugin.easyexcel.UserImportListener;
import com.youlai.system.service.CarUserService;
import com.youlai.system.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * 用户控制器
 *
 * @author haoxr
 * @since 2022/10/16
 */
@Tag(name = "02.中车会用户接口")
@RestController
@RequestMapping("/api/car/users")
@RequiredArgsConstructor
public class CarUserController {

    private final CarUserService carUserService;

    @Operation(summary = "用户分页列表")
    @GetMapping("/page")
    public PageResult<CarUserPageVO> getUserPage(
            @ParameterObject CarUserPageQuery queryParams
    ) {
        IPage<CarUserPageVO> result = carUserService.getUserPage(queryParams);

        return PageResult.success(result);
    }

    @Operation(summary = "我的车库")
    @GetMapping("/getMyGaragePage")
    public PageResult<CarAuthPageVO> getMyGaragePage(
            @ParameterObject CarUserPageQuery queryParams
    ) {
        IPage<CarAuthPageVO> result = carUserService.getMyGaragePage(queryParams);
        return PageResult.success(result);
    }
    @Operation(summary = "用户上传")
    @GetMapping("/getUserAtrPage")
    public PageResult<CarAttPageVO> getUserAtrPage(
            @ParameterObject CarUserPageQuery queryParams
    ) {
        IPage<CarAttPageVO> result = carUserService.getUserAtrPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "我的关注")
    @GetMapping("/getMyFollowPage")
    public PageResult<CarUserPageVO> getMyFollowPage(
            @ParameterObject CarUserPageQuery queryParams
    ) {
        IPage<CarUserPageVO> result = carUserService.getMyFollowPage(queryParams);
        return PageResult.success(result);
    }


    @Operation(summary = "我的分享")
    @GetMapping("/getMySharePage")
    public PageResult<CarSharePageVO> getMySharePage(
            @ParameterObject CarUserPageQuery queryParams
    ) {
        IPage<CarSharePageVO> result = carUserService.getMySharePage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "我的访客")
    @GetMapping("/getMyVisitorPage")
    public PageResult<CarUserPageVO> getMyVisitorPage(
            @ParameterObject CarUserPageQuery queryParams
    ) {
        IPage<CarUserPageVO> result = carUserService.getMyVisitorPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "我的广告")
    @GetMapping("/getMyAdPage")
    public PageResult<CarAdPageVO> getMyAdPage(
            @ParameterObject CarUserPageQuery queryParams
    ) {
        IPage<CarAdPageVO> result = carUserService.getMyAdPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "我的点赞")
    @GetMapping("/getMyLikePage")
    public PageResult<CarUserPageVO> getMyLikePage(
            @ParameterObject CarUserPageQuery queryParams
    ) {
        IPage<CarUserPageVO> result = carUserService.getMyLikePage(queryParams);
        return PageResult.success(result);
    }


    @Operation(summary = "用户VIP分页列表")
    @GetMapping("/pageVip")
    public PageResult<CarUserPageVO> getUserVipPage(
            @ParameterObject CarUserPageQuery queryParams
    ) {
        IPage<CarUserPageVO> result = carUserService.getUserVipPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "用户表单数据")
    @GetMapping("/{userId}/form")
    public Result<UserForm> getUserForm(
            @Parameter(description = "用户ID") @PathVariable Long userId
    ) {
        UserForm formData = carUserService.getUserFormData(userId);
        return Result.success(formData);
    }

    @Operation(summary = "修改用户")
    @PutMapping(value = "/updateUser")
//    @PreAuthorize("@ss.hasPerm('sys:user:edit')")
    public Result updateUser(@RequestBody @Validated CarUserForm userForm) {
        boolean result = carUserService.updateCarUser(userForm.getUserId(), userForm);
        return Result.judge(result);
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("/{ids}")
    public Result deleteUsers(
            @Parameter(description = "用户ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = carUserService.deleteUsers(ids);
        return Result.judge(result);
    }


    @Operation(summary = "修改用户状态")
    @PatchMapping(value = "/{userId}/status")
    public Result updateUserStatus(
            @Parameter(description = "用户ID") @PathVariable Long userId,
            @Parameter(description = "用户状态(1:启用;0:禁用)") @RequestParam Integer status
    ) {
        boolean result = carUserService.update(new LambdaUpdateWrapper<CarUser>()
                .eq(CarUser::getUserId, userId)
                .set(CarUser::getStatus, status)
        );
        return Result.judge(result);
    }

    @Operation(summary = "获取当前登录用户信息")
    @GetMapping("/me")
    public Result<UserInfoVO> getCurrentUserInfo() {
        UserInfoVO userInfoVO = carUserService.getCurrentUserInfo();
        return Result.success(userInfoVO);
    }

    @Operation(summary = "用户导入模板下载")
    @GetMapping("/templateApp")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        String fileName = "用户模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        String fileClassPath = "excel-templates" + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);

        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();

        excelWriter.finish();
    }

    @Operation(summary = "虚拟用户导入模板下载")
    @GetMapping("/templateXnApp")
    public void templateXnApp(HttpServletResponse response) throws IOException {
        String fileName = "虚拟用户模板.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        String fileClassPath = "excel-templates" + File.separator + fileName;
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath);

        ServletOutputStream outputStream = response.getOutputStream();
        ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();

        excelWriter.finish();
    }
    @Operation(summary = "导入用户")
    @PostMapping("/impAppUser")
    public Result importUsers(MultipartFile file) throws IOException {
        UserAppImportListener listener = new UserAppImportListener();
        String msg = ExcelUtils.importExcel(file.getInputStream(), CarUserImportVO.class, listener);
        return Result.success(msg);
    }

    @Operation(summary = "导出用户")
    @GetMapping("/expAppUser")
    public void exportUsers(CarUserPageQuery queryParams, HttpServletResponse response) throws IOException {
        String fileName = "用户数据.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        List<CarUserExportVO> exportUserList = carUserService.listExportUsers(queryParams);
        EasyExcel.write(response.getOutputStream(), CarUserExportVO.class).sheet("用户列表")
                .doWrite(exportUserList);
    }
}
